 package org.lagou.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.lagou.Dao.UserDao;
import org.lagou.Dao.impl.UserDaoImpl;
import org.lagou.bean.ReponseBody;
import org.lagou.bean.UserBean;
import org.lagou.tools.DBTools;

import com.google.gson.Gson;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	/**
	* showdoc
	* @catalog 用户相关/登录功能
	* @title 用户登录
	* @description 用户登录的接口
	* @method post
	* @url http://101.37.77.75:8080/lagouwang/LoginServlet
	* @param email 必选 string 用户名  
	* @param pwd 必选 string 密码  
	* @return {1：成功，0：失败}
	* @remark 项目还在完善中
	* @number 99
	*/
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		QueryRunner query=new QueryRunner(DBTools.ds);
		ReponseBody rb=new ReponseBody();
		Gson gson=new Gson();
		
		String email=request.getParameter("email");
		String pwd=request.getParameter("password");
		
		try {
			Long i=query.query("select count(0) from user where email=? and pwd=?", new ScalarHandler<Long>(),email,pwd);
			if (i>0) {
				UserDao udao = new UserDaoImpl();
				int del=-1;
				List<UserBean> ulist = udao.getByEmailUser(email);
				for (UserBean u : ulist) {
					del = u.getDel();
				}
				if (del==0) {
					rb.setMsg("登录成功");
					rb.setData(ulist);
					//存储session值
					request.getSession().setAttribute("email", email);
				} else {
					rb.setMsg("您的账号已被禁用");
					rb.setStatus(0);
				}
			}else {
				rb.setMsg("用户名或者密码错误");
				rb.setStatus(0);
			}
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
